import history from '@/utils/history'
import { hasToken } from '@/utils/storage'
import React from 'react'
import { Redirect, Route,RouteProps } from 'react-router'

// 预期：
// <AuthRoute path='/profile/chat' component={ProfileChat} />

interface Props extends RouteProps {
  path: string
  // 函数组件类型 FC：Function Component
  component: React.FC
}

export default function AuthRoute({ path, component: Component, ...rest }: Props)  {
  return (
    <Route
    {...rest}
      path={path}
      render={() => {
        if (hasToken()) {
          // 有 token 正常渲染组件
          return <Component />
        } else {
          // 没有 token 重定向到登录页
          return (
            <Redirect
              to={{
                pathname: '/login',
                // 通过 state 存储重定向前的页面路径，用于登录成功后回跳
                state: { from: history.location.pathname },
              }}
            />
          )
        }
      }}
    />
  )
}
